package base

import (
	"crypto/sha256"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"time"
	"walnut/kernel"
)

func UploadFile(w http.ResponseWriter, r *http.Request) {
	// 限制上传文件大小 (10MB)
	r.ParseMultipartForm(10 << 20)

	// 获取上传的文件
	file, handler, err := r.FormFile("file")
	if err != nil {
		kernel.Error(w, err)
		return
	}
	defer file.Close()

	// 创建按日期分目录
	today := time.Now().Format("20060102")
	uploadDir := filepath.Join("uploads", today)
	if err := os.MkdirAll(uploadDir, 0755); err != nil {
		kernel.Error(w, err)
		return
	}

	// 处理文件名：hash文件名但保留扩展名
	ext := filepath.Ext(handler.Filename)
	name := handler.Filename[:len(handler.Filename)-len(ext)]
	hashedName := fmt.Sprintf("%x", sha256.Sum256([]byte(name))) + ext

	// 创建目标文件
	dstPath := filepath.Join(uploadDir, hashedName)
	dst, err := os.Create(dstPath)

	if err != nil {
		kernel.Error(w, err)
		return
	}
	defer dst.Close()

	// 复制文件内容
	if _, err := io.Copy(dst, file); err != nil {
		kernel.Error(w, err)
		return
	}

	kernel.Data(w, map[string]any{
		"filename": handler.Filename,
		"path":     dstPath,
		"size":     handler.Size,
	})
}
